<template>
    <div class="login">
        <el-container>
            <!-- 头部步骤条 -->
            <el-header>
                <el-steps :active="active" finish-status="success">
                    <el-step title="Step 1"></el-step>
                    <el-step title="Step 2"></el-step>
                    <el-step title="Step 3"></el-step>
                </el-steps>
            </el-header>
            <!-- 主体填写表单处 -->
            <el-main style="min-width: 300px;margin: auto;">
                <!-- 验证手机号码或着邮箱 -->
                <el-form v-if="type == '1'" :model="idForm" status-icon :rules="idRules" ref="idForm" class="idForm">
                    <!-- <el-select v-model="selectValue" placeholder="请选择手机或邮箱" style="width: 179px;text-align:center;display: block;float: right;">
                                <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" :disabled="item.disabled" style="margin: auto;"></el-option>
                                </el-select><br/><br/><br/> -->
                    <el-form-item prop="userId">
                        <el-input v-model="idForm.userId" placeholder="请输入邮箱"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" :class="{disabled: !this.canClick}" @click="btnGetCode()" style="width: 260px;">{{content}}</el-button>
                    </el-form-item>
                    <el-form-item prop="code">
                        <el-input v-model="idForm.code" placeholder="请输入验证码"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="btnSubmitForm('idForm')" style="width: 260px;">提交</el-button>
                    </el-form-item>
                </el-form>
                <!-- 填写用户名和设置密码 -->
                <el-form v-else-if="type == '2'" :model="userForm" status-icon :rules="signUpRules" ref="userForm" class="userForm">
                    <el-form-item prop="username">
                        <el-input v-model="userForm.username" placeholder="请输入用户名"></el-input>
                    </el-form-item>
                    <el-form-item prop="pass">
                        <el-input type="password" v-model="userForm.pass" auto-complete="off" placeholder="请输入密码"></el-input>
                    </el-form-item>
                    <el-form-item prop="checkPass">
                        <el-input type="password" v-model="userForm.checkPass" auto-complete="off" placeholder="确认密码"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <!-- 提交用户名和密码 -->
                        <el-button type="primary" @click="btnSubmitForm('userForm')" style="width: 260px;">提交</el-button>
                        <!-- 重置用户名和密码 -->
                        <!-- <el-button @click="resetForm('userFrom')">重置</el-button> -->
                    </el-form-item>
                </el-form>
                <!-- 注册成功提示 -->
                <h3 v-else-if="type == '3'" style="text-align: center;">注册成功!</h3>
            </el-main>
        </el-container>
    </div>
</template>

<script>
    export default {
        data() {
            // 表单一的数据
            var checkId = (rule, value, callback) => {
                if (value === "") {
                    return callback(new Error("必须填写"));
                }
                setTimeout(() => {
                    callback();
                }, 1000);
            };
            var checkCode = (rule, value, callback) => {
                if (value === "") {
                    // ToDo
                    return callback(new Error("验证码不能为空"));
                }
                setTimeout(() => {
                    callback();
                }, 1000);
            };
            // 表单二的数据
            var checkUsername = (rule, value, callback) => {
                if (!value) {
                    return callback(new Error("用户名不能为空"));
                }
                setTimeout(() => {
                    callback();
                }, 1000);
            };
            var validatePass = (rule, value, callback) => {
                if (value === "") {
                    callback(new Error("请输入密码"));
                } else {
                    if (this.userForm.checkPass !== "") {
                        this.$refs.userForm.validateField("checkPass");
                    }
                    callback();
                }
            };
            var validatePass2 = (rule, value, callback) => {
                if (value === "") {
                    callback(new Error("请再次输入密码"));
                } else if (value !== this.userForm.pass) {
                    callback(new Error("两次输入密码不一致!"));
                } else {
                    callback();
                }
            };
            return {
                content: '发送验证码',                          // 按钮里显示的内容
                totalTime: 60,                                //记录具体倒计时时间
                canClick: true,                               //添加canClick
                url: {                                        //请求 Api
                    checkIdApi: this.$Global.url.checkId,
                    getCodeApi: this.$Global.url.emailCode,
                    registerApi: this.$Global.url.register
                },
                isExist: "",                                  // 用户邮箱是否存在
                codeMessage: "",                              // 验证码发送后返回的消息
                verification: "",                             //验证结果
                registerMessage: "",                          //注册结果
                active: 0,                                    // 表单步骤
                type: 1,                                      // 控制表单的显示
                // 表单一的数据
                options: [{
                        value: "选项1",
                        label: "邮箱"
                    },
                    {
                        value: "选项2",
                        label: "手机",
                        disabled: true
                    }
                ],
                selectValue: "",
                idForm: {
                    userId: "",
                    code: ""
                },
                idRules: {
                    userId: [{
                        validator: checkId,
                        trigger: "blur"
                    }],
                    code: [{
                        validator: checkCode,
                        trigger: "blur"
                    }]
                },
                // 表单二的数据
                userForm: {
                    pass: "",
                    checkPass: "",
                    id: ""
                },
                signUpRules: {
                    pass: [{
                        validator: validatePass,
                        trigger: "blur"
                    }],
                    checkPass: [{
                        validator: validatePass2,
                        trigger: "blur"
                    }],
                    username: [{
                        validator: checkUsername,
                        trigger: "blur"
                    }]
                }
            };
        },
        created() {
            // 开发模式
            // if (process.env.NODE_ENV === "development") {
                this.url.checkIdApi = this.$Global.url.baseUrl + this.$Global.url.checkId;
                this.url.getCodeApi = this.$Global.url.baseUrl + this.$Global.url.emailCode;
                this.url.registerApi = this.$Global.url.baseUrl + this.$Global.url.register;
            // }
        },
        methods: {
            /**
             * 提交表单
             */
            btnSubmitForm(formName) {
                this.$refs[formName].validate(valid => {
                    if (valid) {
                        if (formName === 'idForm') {
                            this.verifyCode();
                        } else if (formName === 'userForm') {
                            this.register();
                        }
                    } else {
                        console.log("error submit!!");
                        return false;
                    }
                });
            },
            /**
             * 验证码按钮
             */
            btnGetCode() {
                this.checkExist(); // 检查邮箱并发送验证码
            },
            /**
             * 控制步骤
             */
            next() {
                if (this.active++ > 2) this.active = 0;
            },
            /**
             * 检查用户邮箱并发送验证码
             */
            checkExist() {
                var params = {
                    email: this.idForm.userId
                }
                this.$http.get(this.url.checkIdApi, {
                        params: params
                    })
                    .then(response => {
                        if (response.status == 200) {
                            this.isExist = response.data;
                            // console.log(this.isExist);
                            // 如果用户不存在
                            if (this.isExist.exist) {
                                this.$message(this.isExist.message);
                            } else {
                                // console.log(this.isExist.message)
                                // console.log(this.isExist);
                                this.getCode();
                            }
                        } else {
                            console.log("请求数据失败！");
                        }
                    })
                    .catch(error => {
                        console.log(error);
                    });
            },
            /**
             * 获取验证码
             */
            getCode() {
                var params = {
                    email: this.idForm.userId
                }
                this.$http.get(this.url.getCodeApi, {
                        params: params
                    })
                    .then(response => {
                        if (response.status == 200) {
                            this.codeMessage = response.data;
                            this.$message(this.codeMessage);
                            if (this.codeMessage.success) {
                                this.countDown();
                            }
                        } else {
                            this.$message('请求失败');
                        }
                    })
                    .catch(error => {
                        console.log(error);
                    });
            },
            /**
             * 验证验证码
             */
            verifyCode() {
                var data = {
                    code: this.idForm.code,
                    email: this.idForm.userId
                }
                this.$http
                    .post(this.url.getCodeApi, data)
                    .then(response => {
                        if (response.status == 200) {
                            this.verification = response.data;
                            this.$message(this.verification.message);
                            if (this.verification.success) {
                                // 调整步骤，切换表单
                                this.next();
                                this.type += 1;
                            }
                        } else {
                            this.message("验证码错误");
                        }
                    })
                    .catch(error => {
                        console.log(error);
                    });
            },
            /**
             * 注册账号
             */
            register() {
                var data = {
                    username: this.userForm.username,
                    password: this.userForm.checkPass,
                    email: this.idForm.userId
                }
                this.$http
                    .post(this.url.registerApi, data)
                    .then(response => {
                        if (response.status == 200) {
                            //Todo
                            this.registerMessage = response.data;
                            // alert(this.codeMessage.message)
                            this.$message(this.registerMessage);
                            if (this.registerMessage.success) {
                                this.next();
                                this.next();
                                this.type += 1;
                            }
                        }
                    })
                    .catch(error => {
                        console.log(error);
                    });
            },
            /**
             * 按钮延时点击
             */
            countDown() {
                if (!this.canClick) return // 判断是否能点击
                this.canClick = false;
                this.content = this.totalTime + 's后重新发送' //这里解决60秒不见了的问题
                let clock = window.setInterval(() => {
                    this.totalTime--;
                    this.content = this.totalTime + 's后重新发送'
                    if (this.totalTime < 0) { //当倒计时小于0时清除定时器
                        window.clearInterval(clock)
                        this.content = '重新发送验证码';
                        this.totalTime = 60;
                        this.canClick = true; //这里重新开启
                    }
                }, 1000)
            }
        }
    };
</script>

<style>
    .login {
        width: 80%;
        margin: 10% auto;
    }
    
    .disabled {
        background-color: #ddd;
        border-color: #ddd;
        color: #57a3f3;
        cursor: not-allowed;
    }
</style>
